package com.gzmu.myprint.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzmu.myprint.mapper.ParkMapper;
import com.gzmu.myprint.model.Truck;
import com.alibaba.fastjson.JSONObject;
import com.gzmu.myprint.model.ParkOrder;
import com.gzmu.myprint.model.PrintUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.gzmu.myprint.constant.Constant.PARK_ID;
import static com.gzmu.myprint.constant.Constant.PARK_SECRET;
import static com.gzmu.myprint.vo.CommonUtil.getOpenid;

@Controller
public class ParkController {
    @Autowired
    private ParkMapper parkMapper;

    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @ResponseBody
    @RequestMapping(value = "/getParkOpenid", produces = "text/html;charset=UTF-8")
    public String getParkOpenid(String code){
        System.out.println("+++code: " + code);
        String content = null;
        Map map = new HashMap();
        ObjectMapper mapper = new ObjectMapper();

        PrintUser user = new PrintUser();
        String openid = getOpenid(code,PARK_ID,PARK_SECRET);
        if(!StringUtils.isBlank(openid)){
            openid = openid.replace("\"", "").trim();
            user = parkMapper.findUerByOpenId(openid);
            if (user == null){
                user = new PrintUser();
                user.setOpenid(openid);
                parkMapper.InsertOrUpUser(user);
                user.setId(0);
            }
        }
        try {
            map.put("user", user);
            content = mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    @ResponseBody
    @RequestMapping(value = "/updateParkUser", produces = "text/html;charset=UTF-8")
    public String updateParkUser(HttpServletRequest request){
        String content = null;
        Map map = new HashMap();
        PrintUser user = new PrintUser();
        ObjectMapper mapper = new ObjectMapper();
        String timeStr = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
        String openid = request.getParameter("openid");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String avatarUrl = request.getParameter("avatarUrl");
        String nickName = request.getParameter("nickName");
        String phone = request.getParameter("phone");
        String role = request.getParameter("role");
        user.setOpenid(openid);
        user.setName(name);
        user.setGender(gender);
        user.setAvatarUrl(avatarUrl);
        user.setNickName(nickName);
        user.setPhone(phone);
        user.setRole(Integer.valueOf(role));
        user.setMoney(0.0f);
        user.setTime(timeStr);
        System.out.println("+++openid:" + openid + " role:" + role);
        int res = parkMapper.InsertOrUpUser(user);
        try {
            map.put("res",res);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }

    @ResponseBody
    @RequestMapping(value = "/selectAllPark", produces = "text/html;charset=UTF-8")
    public String selectPrinter() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Truck> list = parkMapper.selecAllPark();
        int max_x = parkMapper.selecMaxX() + 1;
        int max_y = parkMapper.selecMaxY() + 1;

        //int len = max_x * max_y;
        List<Truck> trucks = new ArrayList <>();
        for (int i=0; i<max_x; i++){
            for (int j=0; j<max_y; j++) {
                Truck truck = new Truck();
                truck.setX(i);
                truck.setY(j);
                trucks.add(truck);
            }
        }
        int size = list.size();
        System.out.println("+++size:" + size);
        for (int i=0; i<size; i++){
            int x = list.get(i).getX();
            int y = list.get(i).getY();
            int index = y * max_x + x;
            trucks.get(index).setType("park");
            trucks.get(index).setId(list.get(i).getId());
            trucks.get(index).setTruck(list.get(i).getTruck());
            trucks.get(index).setNumber(list.get(i).getNumber());
            trucks.get(index).setPartition(list.get(i).getPartition());
            trucks.get(index).setStatus(list.get(i).getStatus() + list.get(i).getEngog());
            trucks.get(index).setPlate(list.get(i).getPlate());
            trucks.get(index).setX(list.get(i).getX());
            trucks.get(index).setY(list.get(i).getY());
        }
        map.put("list",trucks);
        map.put("max_x",max_x);
        map.put("max_y",max_y);
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @RequestMapping(value = "/parkOfOrder", produces = "text/html;charset=UTF-8")
    public String parkOfOrder(HttpServletRequest request){
        String content = null;
        Map map = new HashMap();
        Date date = new Date();
        ObjectMapper mapper = new ObjectMapper();
        String truck = request.getParameter("truck");
        String parkid = request.getParameter("parkid");
        String openid = request.getParameter("openid");
        String plate = request.getParameter("plate");
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(date);
        rightNow.add(Calendar.MINUTE,15);
        ParkOrder parkOrder = new ParkOrder();
        parkOrder.setTruck(truck);
        parkOrder.setOpenid(openid);
        parkOrder.setParkid(Integer.valueOf(parkid));
        parkOrder.setPlate(plate);
        parkOrder.setOrders(parkid + "_"+ date.getTime());
        parkOrder.setOrdertime(df.format(date));
        Date stoptime = rightNow.getTime();
        parkOrder.setStoptime(df.format(stoptime));
        parkOrder.setStatus(1);//预订状态
        System.out.println("+++truck: " + truck );
        ParkOrder parkOrderold = parkMapper.selestOrderInfo(openid,"1");
        int res = 0;
        if (parkOrderold==null){
            res = parkMapper.upDateParkOfOrder(truck, 1);
            res &= parkMapper.insertParkOrders(parkOrder);
        }
        System.out.println("+++res:" + res);
        try {
            map.put("res",res);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }

    @ResponseBody
    @RequestMapping(value = "/selectParkUser", produces = "text/html;charset=UTF-8")
    public String selectParkUser(HttpServletRequest request){
        String content = null;
        Map map = new HashMap();
        ObjectMapper mapper = new ObjectMapper();
        String openid = request.getParameter("openid");
        PrintUser user = parkMapper.selectParkUser(openid);
        try {
            map.put("user",user);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }

    @ResponseBody
    @RequestMapping(value = "/selestOrderInfo", produces = "text/html;charset=UTF-8")
    public String selestOrderInfo(HttpServletRequest request){
        String content = null;
        Map map = new HashMap();
        ObjectMapper mapper = new ObjectMapper();
        String openid = request.getParameter("openid");
        String status = request.getParameter("status");
        ParkOrder order = parkMapper.selestOrderInfo(openid,status);
//        if (order!=null){
//            Parker parker = parkMapper.selectParkerById(order.getParkid());
//            order.setName(parker.getName());
//        }
        try {
            map.put("order",order);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }

    @ResponseBody
    @RequestMapping(value = "/selestOrderList", produces = "text/html;charset=UTF-8")
    public String selestOrderList(HttpServletRequest request){
        String content = null;
        Map map = new HashMap();
        ObjectMapper mapper = new ObjectMapper();
        String openid = request.getParameter("openid");
        List<ParkOrder> orders = parkMapper.selestOrderList(openid);
//        if (orders.size()>0){
//            for (int i=0;i<orders.size();i++){
//                Parker parker = parkMapper.selectParkerById(orders.get(i).getParkid());
//                orders.get(i).setName(parker.getName());
//            }
//        }
        try {
            map.put("orders",orders);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }

    @ResponseBody
    @RequestMapping(value = "/cancelOrder", produces = "text/html;charset=UTF-8")
    public String cancelOrder(HttpServletRequest request){
        String content = null;
        Map map = new HashMap();
        Date date = new Date();
        ObjectMapper mapper = new ObjectMapper();
        String id = request.getParameter("id");
        String status = request.getParameter("status");
        String money = request.getParameter("money");
        String truck = request.getParameter("truck");
        ParkOrder parkOrder = new ParkOrder();
        parkOrder.setId(Integer.valueOf(id));
        parkOrder.setStatus(Integer.valueOf(status));
        parkOrder.setMoney(Integer.valueOf(money));
        parkOrder.setExittime(df.format(date));
        int res = parkMapper.cancelOrder(parkOrder);
        res &= parkMapper.upDateParkOfOrder(truck,0);
        try {
            map.put("res",res);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }
}
